package Dao.Impl;

import Dao.UserDAO;
import Dto.UserDto;
import entity.User;

import java.sql.*;

/**
 * @Author Su
 * @Date 2025/4/28 10:32
 * @Version 1.0 （版本号）
 */
public class UserDAOImpl implements UserDAO {
    private Connection connection;

    public UserDAOImpl(Connection connection) {
        this.connection = connection;
    }

    @Override
    public boolean insertUser(User user) throws SQLException {
        String sql = "INSERT INTO user (username, password, email, avatar_url, status) VALUES (?, ?, ?, ?, ?)";
        try (PreparedStatement pstmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getEmail());
            pstmt.setString(4, user.getAvatarUrl());
            pstmt.setInt(5, user.getStatus());

            int affectedRows = pstmt.executeUpdate();
            if (affectedRows == 0) {
                return false;
            }

            try (ResultSet generatedKeys = pstmt.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    user.setUserId(generatedKeys.getInt(1));
                }
            }
            return true;
        }
    }

    @Override
    public User getUserByUsername(String username) throws SQLException {
        String sql = "SELECT * FROM user WHERE username = ?";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, username);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return extractUserFromResultSet(rs);
                }
            }
        }
        return null;
    }

    @Override
    public User getUserByUserId(Integer userId) throws SQLException {
        String sql = "SELECT * FROM user WHERE user_id = ?";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return extractUserFromResultSet(rs);
                }
            }
        }
        return null;
    }

    @Override
    public User getUserByEmail(String email) throws SQLException {
        String sql = "SELECT * FROM user WHERE email = ?";
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, email);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return extractUserFromResultSet(rs);
                }
            }
        }
        return null;
    }

    private User extractUserFromResultSet(ResultSet rs) throws SQLException {
        User user = new User();
        user.setUserId(rs.getInt("user_id"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setEmail(rs.getString("email"));
        user.setAvatarUrl(rs.getString("avatar_url"));
        user.setCreateTime(rs.getTimestamp("create_time"));
        user.setStatus(rs.getInt("status"));
        return user;
    }

    @Override
    public User findByUsername(String username) throws SQLException {
        String sql = "SELECT * FROM user WHERE username = ?";
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, username);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                return new User(
                        rs.getInt("user_id"),
                        rs.getString("username"),
                        rs.getString("password"),
                        rs.getString("email"),
                        rs.getString("avatar_Url"),
                        rs.getDate("create_time"),
                        rs.getInt("status")
                );
            }
            return null;
        }
    }

    @Override
    public void updateLastLoginTime(int userId) throws SQLException {
        String sql = "UPDATE user SET last_login_time = NOW() WHERE user_id = ?";
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setInt(1, userId);
            stmt.executeUpdate();
        }
    }

    @Override
    public boolean resetPassword(String email, String newPassword) throws SQLException{
        try {
            // 1. 更新密码
            try (PreparedStatement stmt = connection.prepareStatement(
                    "UPDATE user SET password = ? WHERE email = ?")) {
                stmt.setString(1, newPassword); // 实际项目中应该加密
                stmt.setString(2, email);
                int result = stmt.executeUpdate();
                return result > 0;
            }
            // 2. 标记验证码为已使用
//            try (PreparedStatement stmt = connection.prepareStatement(
//                    "UPDATE password_reset_tokens SET is_used = 1 WHERE email = ? AND token = ?")) {
//                stmt.setString(1, email);
//                stmt.setString(2, code);
//                stmt.executeUpdate();
//            }
        } catch (SQLException e) {
            connection.rollback();
            throw e;
        } finally {
            connection.setAutoCommit(true);
        }
    }


    @Override
    public boolean isEmailRegistered(String email) throws SQLException {
        try (PreparedStatement stmt = connection.prepareStatement(
                "SELECT user_id FROM user WHERE email = ?")) {
            stmt.setString(1, email);
            ResultSet rs = stmt.executeQuery();
            return rs.next();
        }
    }

    @Override
    public boolean updateUser(UserDto user) throws SQLException {
        String sql = "UPDATE user SET username = ?,email = ?,password = ?,avatar_url = ? WHERE user_id = ?";
        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setString(1, user.getUsername());
            stmt.setString(2, user.getEmail());
            stmt.setString(3, user.getPassword());
            stmt.setString(4, user.getAvatarUrl());
            stmt.setInt(5, user.getUserId());
            int rs = stmt.executeUpdate();
            if (rs > 0) {
                return true;
            }
            return false;
        }
    }
}
